<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员界面 - AI简历解析系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        /* 导航栏样式 */
        .navbar {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        
        .navbar-brand {
            color: #667eea !important;
            font-weight: 700;
            font-size: 1.5rem;
        }
        
        .nav-link {
            color: #555 !important;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .nav-link:hover {
            color: #667eea !important;
        }
        
        .nav-link.active {
            color: #667eea !important;
            font-weight: 600;
        }
        
        /* 容器样式 */
        .main-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            padding: 40px;
            margin: 0 auto;
        }
        
        /* 表单元素样式 */
        .form-label {
            color: #555;
            font-weight: 500;
            margin-bottom: 8px;
            display: block;
        }
        
        .form-control,
        .form-select {
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 12px 16px;
            font-size: 16px;
            transition: all 0.3s ease;
            width: 100%;
        }
        
        .form-control:focus,
        .form-select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        /* 按钮样式 */
        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            border-radius: 10px;
            padding: 12px 24px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .btn-primary:active {
            transform: translateY(0);
        }
        
        /* 用户卡片样式 */
        .user-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            border: none;
        }
        
        .user-card:hover {
            box-shadow: 0 8px 25px rgba(0,0,0,0.08);
            transform: translateY(-2px);
        }
        
        /* 操作按钮样式 */
        .btn-action {
            margin-right: 10px;
            border-radius: 8px;
            padding: 6px 16px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        /* 标题样式 */
        h1 {
            color: #333;
            font-weight: 700;
            text-align: center;
            margin-bottom: 30px;
        }
        
        /* 表格样式 */
        .styled-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            background: white;
        }
        
        .styled-table thead {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }
        
        .styled-table th,
        .styled-table td {
            padding: 16px 20px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .styled-table th {
            font-weight: 600;
            letter-spacing: 0.5px;
        }
        
        .styled-table tbody tr {
            transition: all 0.3s ease;
        }
        
        .styled-table tbody tr:hover {
            background-color: #f8f9ff;
            transform: translateX(2px);
        }
        
        .styled-table tbody tr:last-child td {
            border-bottom: none;
        }
        
        /* 表格中的角色标签样式优化 */
        .styled-table .badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 500;
            font-size: 0.85rem;
        }
        
        /* 表格操作按钮优化 */
        .styled-table .btn {
            margin-right: 6px;
            padding: 6px 12px;
            border-radius: 8px;
            font-size: 0.85rem;
            transition: all 0.3s ease;
        }
        
        .styled-table .btn:hover {
            transform: translateY(-1px);
        }
        
        /* 模态框样式 */
        .modal-content {
            border-radius: 15px;
            border: none;
            box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
        }
        
        .modal-header {
            border-bottom: none;
            padding: 25px;
        }
        
        .modal-title {
            color: #333;
            font-weight: 700;
            font-size: 1.3rem;
        }
        
        .modal-body {
            padding: 25px;
        }
        
        .modal-footer {
            border-top: none;
            padding: 25px;
        }
        
        /* 滚动条样式 */
        ::-webkit-scrollbar {
            width: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .main-container {
                padding: 25px;
            }
            
            .navbar {
                margin-bottom: 15px;
            }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg">
        <div class="container">
            <a class="navbar-brand" href="/"><i class="fas fa-users-cog"></i> AI简历解析系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <div class="navbar-nav ms-auto">
                    <a class="nav-link" href="/">首页</a>
                    <a class="nav-link" href="/resume">简历解析</a>
                    <a class="nav-link active" href="/admin">管理员</a>
                    <div class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user-shield text-primary"></i> <span id="usernameDisplay">管理员</span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/">首页</a></li>
                            <li><a class="dropdown-item" href="/resume">简历解析</a></li>
                            <li><a class="dropdown-item" href="/admin">管理员</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" onclick="logout()"><i class="fas fa-sign-out-alt"></i> 退出登录</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </nav>

    <div class="container main-container">
        <div class="row">

            <div class="col-md-12">
                <!-- 用户管理 -->
                <div class="card border-0 bg-transparent">
                    <div class="card-header bg-transparent border-0 pb-0">
                        <h2 class="text-center text-2xl font-bold text-primary"><i class="fas fa-users-cog"></i> 用户管理</h2>
                    </div>
                    <div class="card-body bg-transparent">
                        <button id="addUserBtn" class="btn btn-primary mb-4 w-100 max-w-xs mx-auto d-block" onclick="showAddModal()">
                            <i class="fas fa-user-plus"></i> 添加用户
                        </button>
                        <div class="table-responsive" style="border-radius: 15px; overflow: hidden;">
                            <table class="styled-table">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>用户名</th>
                                        <th>邮箱</th>
                                        <th>角色</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="userTableBody">
                                    <!-- 动态加载用户数据 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑用户模态框 -->
    <div class="modal fade" id="userModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">添加用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="userForm">
                        <input type="hidden" id="userId">
                        <div class="mb-3">
                            <label class="form-label">用户名</label>
                            <input type="text" class="form-control" id="username" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">邮箱</label>
                            <input type="email" class="form-control" id="email" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">角色</label>
                            <select class="form-select" id="role" required>
                                <option value="USER">普通用户</option>
                                <option value="ADMIN">管理员</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">密码</label>
                            <input type="password" class="form-control" id="password">
                            <small class="form-text text-muted">编辑时留空则不修改密码</small>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveUser()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 重置密码模态框 -->
    <div class="modal fade" id="resetPasswordModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">重置密码</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="resetPasswordForm">
                        <input type="hidden" id="resetUserId">
                        <div class="mb-3">
                            <label class="form-label">新密码</label>
                            <input type="password" class="form-control" id="newPassword" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-warning" onclick="resetPassword()">重置密码</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let users = [];

        // 页面加载时检查权限并加载用户
        document.addEventListener('DOMContentLoaded', function() {
            checkAdminPermission();
            loadUsers();
        });

        // 检查管理员权限
        function checkAdminPermission() {
            const token = localStorage.getItem('token');
            const role = localStorage.getItem('role');
            
            if (!token || role !== 'ADMIN') {
                alert('您没有管理员权限！');
                window.location.href = '/login';
                return;
            }
            
            const username = localStorage.getItem('username');
            document.getElementById('usernameDisplay').textContent = username;
        }

        // 加载用户列表
        async function loadUsers() {
            try {
                const token = localStorage.getItem('token');
                if (!token) {
                    alert('请先登录');
                    logout();
                    return;
                }
                
                // console.log('正在加载用户列表，使用token:', token.substring(0, 20) + '...');
                
                const response = await fetch('/api/admin/users', {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                if (response.ok) {
                    users = await response.json();
                    console.log('加载用户成功:', users);
                    renderUserTable();
                } else if (response.status === 401) {
                    console.error('401认证失败');
                    alert('认证失败，请重新登录');
                    logout();
                } else if (response.status === 403) {
                    console.error('403权限不足');
                    alert('没有权限访问管理员功能');
                    window.location.href = '/';
                } else {
                    const errorText = await response.text();
                    console.error('加载用户失败:', response.status, errorText);
                    alert('加载用户失败: ' + response.status + ' - ' + errorText);
                }
            } catch (error) {
                console.error('加载用户错误:', error);
                alert('加载用户失败: ' + error.message);
            }
        }

        // 渲染用户表格
        function renderUserTable() {
            const tbody = document.getElementById('userTableBody');
            tbody.innerHTML = '';
            
            users.forEach(user => {
                const tr = document.createElement('tr');
                
                // 处理日期格式
                let createdAtStr = '未知';
                if (user.createdAt) {
                    try {
                        createdAtStr = new Date(user.createdAt).toLocaleString();
                    } catch (e) {

                        createdAtStr = user.createdAt || '未知';
                    }
                }
                
                tr.innerHTML = `
                    <td>${user.id}</td>
                    <td>${user.username || ''}</td>
                    <td>${user.email || ''}</td>
                    <td>
                        <span class="badge ${user.role === 'ADMIN' ? 'bg-danger' : 'bg-primary'}">
                            ${user.role === 'ADMIN' ? '管理员' : '普通用户'}
                        </span>
                    </td>
                    <td>${createdAtStr}</td>
                    <td>
                        <button class="btn btn-sm btn-warning" onclick="showEditModal(${user.id})">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button class="btn btn-sm btn-info" onclick="showResetPasswordModal(${user.id})">
                            <i class="fas fa-key"></i> 重置密码
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id})">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </td>
                `;
                tbody.appendChild(tr);
            });
        }

        // 显示添加用户模态框
        function showAddModal() {
            document.getElementById('modalTitle').textContent = '添加用户';
            document.getElementById('userForm').reset();
            document.getElementById('userId').value = '';
            new bootstrap.Modal(document.getElementById('userModal')).show();
        }

        // 显示编辑用户模态框
        function showEditModal(userId) {
            const user = users.find(u => u.id === userId);
            if (user) {
                document.getElementById('modalTitle').textContent = '编辑用户';
                document.getElementById('userId').value = user.id;
                document.getElementById('username').value = user.username;
                document.getElementById('email').value = user.email;
                document.getElementById('role').value = user.role;
                document.getElementById('password').value = '';
                new bootstrap.Modal(document.getElementById('userModal')).show();
            }
        }

        // 保存用户
        async function saveUser() {
            const userId = document.getElementById('userId').value;
            const userData = {
                username: document.getElementById('username').value,
                email: document.getElementById('email').value,
                role: document.getElementById('role').value,
                password: document.getElementById('password').value
            };

            const url = userId ? `/api/admin/users/${userId}` : '/api/admin/users';
            const method = userId ? 'PUT' : 'POST';

            try {
                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + localStorage.getItem('token')
                    },
                    body: JSON.stringify(userData)
                });

                if (response.ok) {
                    bootstrap.Modal.getInstance(document.getElementById('userModal')).hide();
                    loadUsers();
                    alert('保存成功！');
                } else {
                    alert('保存失败！');
                }
            } catch (error) {
                console.error('Error:', error);
                alert('保存失败！');
            }
        }

        // 显示重置密码模态框
        function showResetPasswordModal(userId) {
            document.getElementById('resetUserId').value = userId;
            document.getElementById('newPassword').value = '';
            new bootstrap.Modal(document.getElementById('resetPasswordModal')).show();
        }

        // 重置密码
        async function resetPassword() {
            const userId = document.getElementById('resetUserId').value;
            const newPassword = document.getElementById('newPassword').value;

            try {
                const response = await fetch(`/api/admin/users/${userId}/reset-password`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + localStorage.getItem('token')
                    },
                    body: JSON.stringify({ newPassword })
                });

                if (response.ok) {
                    bootstrap.Modal.getInstance(document.getElementById('resetPasswordModal')).hide();
                    loadUsers();
                    alert('密码重置成功！');
                } else {
                    alert('密码重置失败！');
                }
            } catch (error) {
                console.error('Error:', error);
                alert('密码重置失败！');
            }
        }

        // 删除用户
        async function deleteUser(userId) {
            if (!confirm('确定要删除这个用户吗？')) return;

            try {
                const response = await fetch(`/api/admin/users/${userId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('token')
                    }
                });

                if (response.ok) {
                    loadUsers();
                    alert('删除成功！');
                } else {
                    alert('删除失败！');
                }
            } catch (error) {
                console.error('Error:', error);
                alert('删除失败！');
            }
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('token');
            localStorage.removeItem('username');
            localStorage.removeItem('role');
            window.location.href = '/login';
        }
    </script>
</body>
</html>